package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.DealerCarBean;
import com.bjesc_b2c.app.appraiset.bean.XDPostBean;
import com.bjesc_b2c.app.appraiset.mvp.presenter.XDPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.XDPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.XDView;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.EnddowFragment;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.ExaminingFragment;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.KentnopassFragment;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.PublishpassFragment;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.TrackFragment;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.AddCarDialog;
import com.bjesc_b2c.app.appraiset.widget.dialog.DateTimeDialogOnlyYMD;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.KeyWordsPop;
import com.example.codeutils.utils.TimeUtils;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItemAdapter;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItems;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.MapUtil;

import java.util.Date;

import butterknife.Bind;
import butterknife.OnClick;
import rxbus_base.RxBus;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.TokenBean;

/**
 * Created by yidong on 2017/7/26.
 * 巡店界面
 */

public class PatrolShopActivity extends BaseActivity implements DateTimeDialogOnlyYMD.MyOnDateSetListener, XDView, AddCarDialog.CallBack {
    @Bind(R.id.viewpager)
    ViewPager mViewPager;
    @Bind(R.id.viewpager_tab)
    SmartTabLayout mViewpagerTab;
    private DateTimeDialogOnlyYMD dateTimeDialog;
    @Bind(R.id.tv_start_time)
    TextView startTimeTv;
    @Bind(R.id.tv_end_time)
    TextView endTimeTv;
    @Bind(R.id.tv_find_type)
    TextView tvfindTitle;
    @Bind(R.id.titleView)
    View titleView;

    @Bind(R.id.edit_search_name)
    EditText searchEdit;
    private Intent intent = new Intent();
    private int type = 1;
    private int timeType;
    private String dealerId;
    private XDPresenter xdPresenter;
    private XDPostBean postBean;
    private KeyWordsPop keyWordsPop;

    @Override
    protected int getLayout() {
        return R.layout.activity_patrol_shop;
    }

    @Override
    protected void initEventAndData() {
        dealerId = getIntent().getStringExtra("carFofId");
        CustomSharedPreferences.saveString(this, new MapUtil().put(KeyBean.DEALER_ID.valueOf(), dealerId).build(), KeyBean.FILE_NAME.valueOf());
        Logger.d("dealerId===" + dealerId);
        postBean = new XDPostBean();
        postBean.setDealer_id(dealerId);
        postBean.setStatus("PUBLISHPASS");
        final LayoutInflater inflater = LayoutInflater.from(this);
        final int[] tabTitles = {R.string.on_frame, R.string.down_frame, R.string.await_check, R.string.no_pass, R.string.await_detect};
        FragmentPagerItems pages = FragmentPagerItems.with(this)
                .add(R.string.on_frame, PublishpassFragment.class)
                .add(R.string.down_frame, EnddowFragment.class)
                .add(R.string.await_check, ExaminingFragment.class)
                .add(R.string.no_pass, KentnopassFragment.class)
                .add(R.string.await_detect, TrackFragment.class)
                .create();
        FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(getSupportFragmentManager(), pages);
        mViewPager.setOffscreenPageLimit(pages.size());
        mViewPager.setAdapter(adapter);
        mViewpagerTab.setCustomTabView(new SmartTabLayout.TabProvider() {
            @Override
            public View createTabView(ViewGroup container, int position, PagerAdapter adapter) {
                View view = inflater.inflate(R.layout.layout_navigation_top_item, container, false);
                TextView titleView = (TextView) view.findViewById(R.id.txt_title);
                titleView.setText(tabTitles[position % tabTitles.length]);
                return view;
            }
        });
        mViewpagerTab.setViewPager(mViewPager);
        dateTimeDialog = new DateTimeDialogOnlyYMD(this, this, true, true, true);
        searchEdit.addTextChangedListener(mTextWatcher);
        startTimeTv.setText(TimeUtils.date2String(new Date(), TimeUtils.YMD_PATTERN));
        endTimeTv.setText(TimeUtils.date2String(new Date(), TimeUtils.YMD_PATTERN));
        getIntentFuzzyQueryA();
    }

    @Override
    protected void createPresenter() {
        xdPresenter = new XDPresenterImpl(this);
    }

    @Override
    public void loadStart() {
        showLoading();
    }

    @Override
    public void loadCompleted() {
        cancelLoading();
    }

    @Override
    public void loadFailure() {
        cancelLoading();
    }

    @Override
    public void getDealerCars(DealerCarBean bean) {


    }

    @OnClick({R.id.tv_add_car, R.id.tv_find_type, R.id.tv_start_time, R.id.tv_end_time, R.id.rl_return, R.id.btn_finish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_return:
                finish();
                break;
            case R.id.tv_add_car:
                AddCarDialog carDialog = new AddCarDialog(this, this);
                carDialog.show();
                break;
            case R.id.tv_find_type:
                keyWordsPop = new KeyWordsPop(this, popListener);
                keyWordsPop.showAsDropDown(titleView, 40, 0);
                break;
            case R.id.tv_start_time:
                if (dateTimeDialog != null) {
                    dateTimeDialog.show();
                    timeType = 0;
                }

                break;
            case R.id.tv_end_time:
                if (dateTimeDialog != null) {
                    dateTimeDialog.show();
                    timeType = 1;
                }
                break;
            case R.id.btn_finish://盘库完成
                xdPresenter.alreadyInventory(this, dealerId);
                break;
        }
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            switch (view.getId()) {
                case R.id.tv_car_name:
                    tvfindTitle.setText("车辆名称");
                    type = 1;
                    searchEdit.setText("");
                    searchEdit.setHint("请输入车辆名称");
                    break;
                case R.id.tv_car_number:
                    tvfindTitle.setText("车牌号");
                    searchEdit.setText("");
                    searchEdit.setHint("请输入车牌号");
                    type = 2;
                    break;
                case R.id.tv_car_vin:
                    tvfindTitle.setText("VIN");
                    searchEdit.setText("");
                    searchEdit.setHint("请输入VIN码");
                    type = 3;
                    break;

            }
            if (keyWordsPop.isShowing()) {
                keyWordsPop.dismiss();
            }
        }
    };

    @Override
    public void callBack(String vin) {
        if (!TextUtils.isEmpty(dealerId) && xdPresenter != null)
            xdPresenter.addCar(this, dealerId, vin);
    }

    @Override
    public void onDateSet(Date date) {
        if (timeType == 0) {
            startTimeTv.setText(TimeUtils.date2String(date, TimeUtils.YMD_PATTERN));
            RxBus.getInstance().sendData("start_time", TimeUtils.date2Millis(date));
        } else {
            endTimeTv.setText(TimeUtils.date2String(date, TimeUtils.YMD_PATTERN));
            RxBus.getInstance().sendData("end_time", TimeUtils.date2Millis(date));
        }
    }

    @Override
    public void panKuSuccess(TokenBean bean) {
        if(bean.getStatus_code() == 0){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try
                    {
                        Thread.sleep(2000);
                        setResult(2);
                        finish();
                    }
                    catch (InterruptedException e) {
                    }

                }
            }).start();

        }
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
//            RxBus.getInstance().sendData("keyWord", searchEdit.getText().toString());
        }
    };

    //把 确认键变成搜索键 跳过去
    public void getIntentFuzzyQueryA() {
//搜索框。EditView 新建一个事件。
        searchEdit.setOnKeyListener(new View.OnKeyListener() {//输入完后按键盘上的搜索建
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //判断是否按下。
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    //判断是否是回车键
                    if (keyCode == event.KEYCODE_ENTER) {
                        String keyWord = searchEdit.getText().toString();
                        //为NULL 判断
                        if (!TextUtils.isEmpty(keyWord)) {
                            intent.putExtra("type", type);
                            intent.putExtra("keyWord", keyWord);
                            Logger.d("RxBus=");
                            RxBus.getInstance().sendData(PatrolShopActivity.class.getName(), intent);
                            Logger.d("RxBus=");
                        }
                    }
                }
                return false;
            }

        });
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getRequestMark().equals(PublishpassFragment.class.getName())){
             if (rxBusBean.getO() instanceof DealerCarBean ){
                 DealerCarBean bean = (DealerCarBean)rxBusBean.getO();
                 TextView textView_1 = (TextView) mViewpagerTab.getTabAt(0).findViewById(R.id.txt_number);
                 textView_1.setText(bean.getCount().getPUBLISHPASS());
                 TextView textView_2 = (TextView) mViewpagerTab.getTabAt(1).findViewById(R.id.txt_number);
                 textView_2.setText(bean.getCount().getENDDOWN());
                 TextView textView_3 = (TextView) mViewpagerTab.getTabAt(2).findViewById(R.id.txt_number);
                 textView_3.setText(bean.getCount().getEXAMINING());
                 TextView textView_4 = (TextView) mViewpagerTab.getTabAt(3).findViewById(R.id.txt_number);
                 textView_4.setText(bean.getCount().getKENTNOPASS());
                 TextView textView_5 = (TextView) mViewpagerTab.getTabAt(4).findViewById(R.id.txt_number);
                 textView_5.setText(bean.getCount().getTRACK());
             }
        }
    }
}

